package com.cartoonrabbit.controller;

import com.cartoonrabbit.service.IImageHandleService;
import com.cartoonrabbit.vo.RespBean;
import com.cartoonrabbit.wxapp.utils.ImageUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.security.Principal;
import java.util.concurrent.locks.ReentrantLock;

@RestController
@RequestMapping("/image")
@Api(tags = "图片相关接口")
public class ImageHandleController {

    public static ReentrantLock reentrantLock=new ReentrantLock();
    @Autowired
    private IImageHandleService imageHandleService;

    @ApiOperation("图片转卡通图")
    @PostMapping("/tranforCartoon")
    @PreAuthorize("@ss.permitAll()")
    public RespBean tranforCartoon(@RequestParam("imageFile")MultipartFile imageFile,
                                   @RequestParam(value = "type",defaultValue = "1") Integer type,
                                   Principal principal){
        if (reentrantLock.tryLock()){
            if (ObjectUtils.isEmpty(principal)||ObjectUtils.isEmpty(principal.getName())){
                return RespBean.fail(401,"用户为授权，请重新登录");
            }
            if (ObjectUtils.isEmpty(imageFile)||imageFile.isEmpty()){
                return RespBean.fail(500,"上传图片为空");
            }
            try {
                RespBean respBean = imageHandleService.tranforCartoon(imageFile, type, principal.getName());
                return respBean;
            }finally {
                reentrantLock.unlock();
            }
        }else {
            return RespBean.fail("服务器正忙，请稍后生成");
        }
    }
}
